# -*- coding: utf-8 -*-
# This code written by ChanGOGOGO
"""
蚂蚁接口
"""
import hmac
import time
from util import *

my_faker = faker_object = Faker("zh_CN")


class MarketingShieldAPI:
    def __init__(self, app_key, app_secret, ip="xxx", port=9705):
        self.app_key = app_key
        self.app_secret = app_secret
        self.timestamp = str(int(time.time() * 1000))
        self.headers = self.get_headers()
        self.token = app_key
        self.ip = ip
        self.port = port

    def gen_sign(self):
        """生成签名"""
        data = self.app_key + self.timestamp
        key = self.app_secret.encode("utf-8")
        data = data.encode("utf-8")
        sign = hmac.new(key, data, hashlib.sha1)
        return base64.b64encode(sign.digest()).decode("utf-8")

    def get_headers(self):
        """生成请求头"""
        headers = {
            "appKey": self.app_key,
            "timestamp": self.timestamp,
            "sign": self.gen_sign(),
            "Content-Type": "application/json;charset=utf-8",
            "Accept": "application/json;charset=utf-8",
            "encrypt": None,
        }
        logging.info(f"生成请求头：\n{data2beautify(headers)}")
        return headers

    @staticmethod
    def generate_customers(
        custom_variables: dict,
        total_phone=1,
        tag=None,
        client_url=None,
        key_template="MOBILE",
        biz_properties={},
    ):
        customers = list()
        for _ in range(total_phone):
            phone = random_phone()
            if key_template == "MOBILE_MD5":
                phone = encrypy_md5(phone)
            elif key_template == "MOBILE_AES":
                phone = encrypt_aes(phone)
            customer_info = {
                "tag": tag,
                "clientUrl": client_url,
                "customerKey": phone,
                "keyTemplate": key_template,
                "properties": custom_variables,
                "bizProperties": biz_properties,
            }
            customers.append(customer_info)
        return customers

    def import_phone(
        self,
        task_id,
        total_phone,
        custom_variables,
        tag=None,
        client_url=None,
        key_template="MOBILE",
        biz_properties={},
        import_transaction_type=1,
    ):
        """导入手机号"""
        # 生成客户清单
        customers = self.generate_customers(
            custom_variables=custom_variables,
            total_phone=total_phone,
            tag=tag,
            client_url=client_url,
            key_template=key_template,
            biz_properties=biz_properties,
        )
        url = f"http://{self.ip}:{self.port}/yicall/api/alidun/importCustomers"
        body = {
            "requestId": random_str(),
            "taskId": task_id,
            "importTransactionType": import_transaction_type,
            "customers": customers,
        }
        res = post_json(url, body, headers=self.headers, log_switch=True)
        return res

    def get_task_list(self, task_id=None, last_call_time=None):
        """获取任务列表"""
        url = f"http://{self.ip}:{self.port}/yicall/api/alidun/getCallTaskList"
        body = {"taskId": task_id, "lastCallTime": last_call_time}
        res = post_json(url, body, headers=self.headers)
        return res

    def get_batch_task_list(self, task_ids: list = None):
        """批量获取任务列表"""
        url = f"http://{self.ip}:{self.port}/yicall/api/alidun/getCallBatchTaskList"
        body = {"taskIdList": task_ids}
        res = post_json(url, body, headers=self.headers)
        return res


if __name__ == "__main__":
    """PET环境"""
    # app_key = "16385000"
    # app_secret = "4e989dbd439e4e63954972b781edea3a"
    # ms_api = MarketingShieldAPI(app_key, app_secret, ip="172.18.160.131", port=9705)

    """PLS环境-uni-pre"""
    app_key = "16385003"
    app_secret = "darriSdJhQvlDQuWJAXOLlHbzjAXAQAV"
    ms_api = MarketingShieldAPI(
        app_key, app_secret, ip="openapi-aibpo.ibot.ai", port=9705
    )

    """导入手机号"""
    t_task_id = 42
    t_data_num = 1
    t_customers = generate_customers(t_data_num, key_template="MOBILE", tag="XXX")
    t_res = ms_api.import_phone(t_task_id, t_customers)

    """查询任务列表"""
    # t_task_id = None
    # t_last_call_time = None
    # t_res = ms_api.get_task_list(t_task_id, t_last_call_time)
    # # t_res = ms_api.get_task_list()
    # task_list = t_res.get('data')

    """批量查询任务"""
    # t_task_ids = [584]
    # t_res = ms_api.get_batch_task_list(t_task_ids)
